package com.hmall.item.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.item.domain.dto.ItemDocDTO;
import com.hmall.item.domain.query.ItemPageQuery;
import com.hmall.item.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 虎哥
 */
@Slf4j
@Service
@RefreshScope
@Primary
public class SearchServiceImpl implements ISearchService {
    @Value("${hm.es.aggregationCount}")
    private Integer aggregationCount;
    @Autowired
    private RestHighLevelClient client;

    /**
     * 1、商品搜索
     * @param params 搜索条件参数
     * @return
     */
    @Override
    public PageDTO<ItemDocDTO> search(ItemPageQuery params) {
        int pageSize = params.getPageSize();
        int pageNo = params.getPageNo();
        try {
            // 1.准备请求参数
            SearchRequest searchRequest = new SearchRequest("items");
            SearchSourceBuilder source = searchRequest.source();
            source.trackTotalHits(true);

            // 1.1、构建查询条件
            QueryBuilder queryBuilder = this.buildBasicQuery(params);
            source.query(queryBuilder);

            // 1.2、构建分页和排序参数
            source.from((pageNo - 1) * pageSize).size(pageSize);
            if (StrUtil.isNotBlank(params.getSortBy())) {
                source.sort(params.getSortBy(), params.getIsAsc() ? SortOrder.ASC : SortOrder.DESC);
            }

            //1.3、构建高亮 Builder
            HighlightBuilder highlight = SearchSourceBuilder.highlight().field("name").requireFieldMatch(false);
            source.highlighter(highlight);

            //2、执行查询，解析结果
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            PageDTO<ItemDocDTO> pageDTO = this.parseResponseResult(response);

            Long totalPage = pageDTO.getTotal() / pageSize == 0 ?
                    pageDTO.getTotal() / pageSize : pageDTO.getTotal() / pageSize + 1;
            pageDTO.setPages(totalPage);
            return pageDTO;
        } catch (Exception e) {
            log.error("搜索数据失败", e);
            throw new BizIllegalException("搜索数据失败");
        }
    }

    /**
     * 构建查询条件
     */
    private AbstractQueryBuilder buildBasicQuery(ItemPageQuery params) {
        // 1.准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1.关键字搜索，match查询，放到must中
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 不为空，根据关键字查询
            boolQuery.must(QueryBuilders.matchQuery("name", key));
        } else {
            // 为空，查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 1.2.品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3.分类
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 1.4.价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        // 2.算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery, // 原始查询，boolQuery
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ // function数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), // 过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(100) // 算分函数
                        )
                }
        ).boostMode(CombineFunction.SUM);
        // 3.返回查询条件
        return functionScoreQuery;
    }

    /**
     * 解析响应结果
     * @param response
     * @return
     */
    private PageDTO<ItemDocDTO> parseResponseResult(SearchResponse response) {
        List<ItemDocDTO> results = new ArrayList<>();
        SearchHits searchHits = response.getHits();
        //4.1、结果集总数
        long total = searchHits.getTotalHits().value;
        System.out.println("结果集总数 = " + total);
        //4.2、结果集数据
        SearchHit[] hits = searchHits.getHits();
        if (ObjectUtil.isNotEmpty(hits)) {
            for (SearchHit hit : hits) {
                String dataJson = hit.getSourceAsString();
                ItemDocDTO itemDocDTO = JSON.parseObject(dataJson, ItemDocDTO.class);

                // 4.3、解析高亮结果
                Map<String, HighlightField> highlightMap = hit.getHighlightFields();
                if (ObjectUtil.isNotEmpty(highlightMap)) {
                    for (HighlightField highlightField : highlightMap.values()) {
                        String fieldName = highlightField.getName(); //高亮字段名称
                        String highlightResult = highlightField.getFragments()[0].string();  //高亮结果
                        try {
                            Field field = ItemDocDTO.class.getDeclaredField(fieldName); //反射根据字段名称获取字段对象
                            field.setAccessible(true);  //暴力反射
                            field.set(itemDocDTO, highlightResult);  //动态赋值
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                results.add(itemDocDTO);
            }
        }
        return new PageDTO<>(total, null, results);
    }

    /**
     * 2、商品聚合查询（聚合查询符合条件的所有 【品牌】 和 【分类】）
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(ItemPageQuery params) {
        try {
            SearchRequest searchRequest = new SearchRequest("items");
            SearchSourceBuilder source = searchRequest.source().size(0);

            // 1、构建查询条件
            QueryBuilder queryBuilder = buildBasicQuery(params);
            source.query(queryBuilder);

            // 2、构建桶聚合
            TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brand").size(aggregationCount);
            TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("categoryAgg").field("category").size(aggregationCount);
            source.aggregation(brandAgg).aggregation(categoryAgg);

            // 3、发起查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 4、获取聚合结果
            Aggregations aggregations = searchResponse.getAggregations();
            Map<String, List<String>> filters = new HashMap<>(2);
            // 4.1.解析品牌
            List<String> brandList = this.getAggResultForAggName(aggregations, "brandAgg");
            filters.put("brand", brandList);
            // 4.2.解析分类
            List<String> categoryList = this.getAggResultForAggName(aggregations, "categoryAgg");
            filters.put("category", categoryList);

            return filters;
        } catch (Exception e) {
            log.error("聚合查询失败", e);
            throw new BizIllegalException("聚合查询失败");
        }
    }

    /**
     * 解析聚合结果
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggResultForAggName(Aggregations aggregations, String aggName) {
        Terms agg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = agg.getBuckets();
        List<String> results = new ArrayList();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            System.err.println("key = " + key + ", docCount = " + docCount);
            results.add(key);
        }
        return results;
    }
}
